package com.example.park_management.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Assert;
import com.baomidou.mybatisplus.extension.conditions.query.QueryChainWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.park_management.common.PageParam;
import com.example.park_management.common.Result;
import com.example.park_management.domain.Assets;
import com.example.park_management.domain.Buildings;
import com.example.park_management.domain.Floors;
import com.example.park_management.domain.Rooms;
import com.example.park_management.domain.vo.RoomVo;
import com.example.park_management.domain.vo.RoomsQueryVO;
import com.example.park_management.service.AssetsService;
import com.example.park_management.service.BuildingsService;
import com.example.park_management.service.FloorsService;
import com.example.park_management.service.RoomsService;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;


@RestController
@RequestMapping("/rooms")
public class RoomsController {

    @Resource
    RoomsService roomsService;

    @Resource
    AssetsService assetsService;

    @Resource
    FloorsService floorsService;


    @PostMapping("/")
    public Result add(@RequestBody RoomVo rooms) {
        try{
            if (rooms.getFloorId().equals(0)){
                return Result.fail("必填属性为空");
            }
            Rooms rooms1 = new Rooms();
            rooms1.setRoomNumber(rooms.getRoomNumber());
            rooms1.setFloorId(rooms.getFloorId());
            rooms1.setReleaseTime(rooms.getReleaseTime());
            int roomId = roomsService.createRoom(rooms1);

            Assets assets = new Assets();
            assets.setRoomId(roomId);
            assets.setOwnerId(Integer.parseInt(rooms.getOwnerId()));
            boolean save = assetsService.save(assets);
            if (save){
                return Result.success();
            }
            return Result.fail();
        }catch (Exception e) {
            return Result.fail("输入格式异常！");
        }
    }

    @PutMapping("/")
    public Result update(@RequestBody RoomVo rooms) {
        try{
        if (rooms.getFloorId().equals(0)){
            return Result.fail("必填属性为空");
        }
        Rooms rooms1 = new Rooms();
        rooms1.setRoomId(rooms.getRoomId());
        rooms1.setRoomNumber(rooms.getRoomNumber());
        rooms1.setFloorId(rooms.getFloorId());
        rooms1.setReleaseTime(rooms.getReleaseTime());
        roomsService.updateById(rooms1);
        QueryWrapper<Assets> assetsQueryWrapper = new QueryWrapper<>();
        assetsQueryWrapper.in("room_id", rooms1.getRoomId());
        assetsService.remove(assetsQueryWrapper);

        String ownerIdStr = rooms.getOwnerId();
        if (ownerIdStr != null && !ownerIdStr.trim().isEmpty()) {
            int ownerId = Integer.parseInt(ownerIdStr);
            Assets assets = new Assets();
            assets.setRoomId(rooms1.getRoomId());
            assets.setOwnerId(ownerId);
            int roomId = rooms1.getRoomId();
            // 根据ownerId是否存在来决定是保存新关联还是忽略此步骤
            boolean isAssociated = assetsService.isAssetAssociatedWithRoom(roomId, ownerId); // 假设此方法用于检查关联是否已存在
            if (!isAssociated) {
                boolean save = assetsService.save(assets);
                if (!save) {
                    // 如果保存失败，考虑是否需要回滚之前的房间更新操作或采取其他补偿措施
                    return Result.fail("房间更新成功，但关联所有者失败");
                }
            }
        }

        }catch (Exception e) {
            return Result.fail("输入格式异常！");
        }

// 不论ownerId是否处理，只要房间信息更新成功就视为整体操作成功
        return Result.success();
    }

    @DeleteMapping("/{roomId}")
    public Result delete(@PathVariable Integer roomId) {
        // 新增：检查房间是否与任何楼层关联
        QueryWrapper<Floors> floorCheckWrapper = new QueryWrapper<>();
        floorCheckWrapper.eq("room_id", roomId); // 假设`Floors`表中引用`Rooms`表的字段名为`room_id`
        if ((int) floorsService.count(floorCheckWrapper) > 0) {
            return Result.fail("该房间已被分配至楼层，不能直接删除");
        }

        // 保留原有逻辑：检查房间是否有所有者关联
        QueryWrapper<Assets> ownerCheckWrapper = new QueryWrapper<>();
        ownerCheckWrapper.eq("room_id", roomId).isNotNull("owner_id");
        if ((int) assetsService.count(ownerCheckWrapper) > 0) {
            return Result.fail("该房间有所有者关联，不能删除");
        }

        // 删除与房间关联的所有Assets记录
        QueryWrapper<Assets> assetsQueryWrapper = new QueryWrapper<>();
        assetsQueryWrapper.in("room_id", roomId);
        assetsService.remove(assetsQueryWrapper);

        // 尝试删除房间
        if (roomsService.removeById(roomId)) {
            return Result.success();
        } else {
            return Result.fail("房间删除操作失败，请重试");
        }
    }


    @PostMapping("/page")
    public Result page(@RequestBody PageParam<RoomsQueryVO> pageParam) {
        Page<Rooms> roomsPage = new Page<>(pageParam.getPageNum(), pageParam.getPageSize());
        QueryWrapper<Rooms> roomsQueryWrapper = new QueryWrapper<>();
        if (pageParam.getData() != null){
            if (pageParam.getData().getOwnersId() != null){
                List<Integer> roomsIdList = assetsService.list(new QueryWrapper<Assets>().eq("owner_id", pageParam.getData().getOwnersId())).stream().map(Assets::getRoomId).collect(Collectors.toList());
                roomsQueryWrapper.in("room_id", roomsIdList);
            }
            if(pageParam.getData().getBuildingId() != null){
               List<Integer> floorIdList = floorsService.list(new QueryWrapper<Floors>().eq("building_id", pageParam.getData().getBuildingId())).stream().map(Floors::getFloorId).collect(Collectors.toList());
                roomsQueryWrapper.in("floor_id", floorIdList);
            }
            if (pageParam.getData().getFloorId() != null){
                roomsQueryWrapper.in("floor_id", pageParam.getData().getFloorId());
            }
        }
        roomsService.page(roomsPage,roomsQueryWrapper);
        List<Rooms> records = roomsPage.getRecords();
        List<RoomVo> newList = new ArrayList<>();
        for (Rooms rooms: records) {
            List<Assets> ownerList = assetsService.getOwnerList(rooms.getRoomId());
            String collect = ownerList.stream()
                    .map(obj -> String.valueOf(obj.getOwnerId()))
                    .collect(Collectors.joining(","));
            RoomVo roomVo = new RoomVo(rooms.getRoomId(), rooms.getRoomNumber(), rooms.getFloorId(), rooms.getReleaseTime(), collect);
            newList.add(roomVo);
        }
        return Result.success(newList, roomsPage.getTotal());
    }

}
